package cn.rubbit.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import cn.rubbit.entity.BaseBean;
import freemarker.cache.FileTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class GenerateFile {
	private static List<TemplateLoader> list = new ArrayList<TemplateLoader>();
	static {
		try {
			list.add(new FileTemplateLoader(new File(GenerateFile.class.getClass().getResource("/").getFile())));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void setLoadPath(TemplateLoader tl) {
		list.add(tl);
	}

	public static void generateFTL(String targetPath, String tempPath, BaseBean baseBean) {
		Configuration cfg = new Configuration();
		File file = new File(targetPath);
		if (!file.exists()) {
			file.getParentFile().mkdirs();
		}
		try {
			TemplateLoader[] tls = new TemplateLoader[list.size()];
			MultiTemplateLoader mtl = new MultiTemplateLoader(list.toArray(tls));
			cfg.setTemplateLoader(mtl);
			file.createNewFile();
			Template temp = cfg.getTemplate(new File(tempPath).getName(), "UTF-8");
			Writer out = new OutputStreamWriter(new FileOutputStream(file));
			temp.process(baseBean.toMap(), out);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		}
	}
}
